package com.example.syyao.myapp.Personal;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.syyao.myapp.MainActivity;
import com.example.syyao.myapp.R;

import com.example.syyao.myapp.Response.Get_response;
import com.example.syyao.myapp.Tool.MyGlideEngine;
import com.example.syyao.myapp.WebContact.JsonUtil;
import com.example.syyao.myapp.WebContact.WebAccessTools;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import me.imid.swipebacklayout.lib.app.SwipeBackActivity;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import static com.example.syyao.myapp.MainActivity.MODE;
import static com.example.syyao.myapp.MainActivity.PREFERENCE_NAME;

public class Setting extends SwipeBackActivity {
    private LinearLayout set_back;
    private LinearLayout set_name;
    private LinearLayout set_about;
    private ImageView set_exit;
    private ImageView headpicture;

    private TextView nickname;
    private ImageView changename;

    private Uri uri;
    private String pic;
    Get_response get_response;

    private static final int REQUEST_CODE_CHOOSE = 23;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.setting);
        overridePendingTransition(R.anim.slide_in_right,R.anim.slide_out_right);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        }

        headpicture= (ImageView) findViewById(R.id.set_head_picture);
        headpicture.setOnClickListener(new chang_picture());
        nickname = (TextView) findViewById(R.id.nickname);


        changename = (ImageView) findViewById(R.id.changename);
        Intent intent=getIntent();
        String name=intent.getStringExtra("nickname");
        String picture=intent.getStringExtra("headpicture");

        RequestOptions options = new RequestOptions()
                .placeholder(R.mipmap.login_pic)		;
        Glide.with(Setting.this).asBitmap().load(picture).apply(options).into(headpicture);

        nickname.setText(name);
        changename.setOnClickListener(new btn_changename());

        set_back=(LinearLayout) findViewById(R.id.set_back);
        set_back.setOnClickListener(new setback_lis());

        set_name=(LinearLayout) findViewById(R.id.set_name);
        set_name.setOnClickListener(new btn_changename());

        set_about=(LinearLayout) findViewById(R.id.set_about);
        set_about.setOnClickListener(new setabout_lis());

        set_exit=(ImageView)findViewById(R.id.set_exit);
        set_exit.setOnClickListener(new setexit_lis());
    }


    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(0,R.anim.slide_out_right);
    }


    //跳转
    public class btn_changename implements View.OnClickListener{

        @Override
        public void onClick(View v) {
            Intent intent = new Intent(Setting.this, changename.class);
            startActivity(intent);
        }
    }

    //返回
    public class setback_lis implements View.OnClickListener{

        @Override
        public void onClick(View v) {
            finish();
        }
    }

    //关于
    public class setabout_lis implements View.OnClickListener{

        @Override
        public void onClick(View v) {
            Intent intent = new Intent(Setting.this, app_about.class);
            startActivity(intent);
        }
    }

    //退出登录
    public class setexit_lis implements View.OnClickListener{

        @Override
        public void onClick(View v) {

            SharedPreferences sharedPreferences=getSharedPreferences(PREFERENCE_NAME,MODE);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.clear();
            editor.apply();

            Intent intent = new Intent();
            intent.setAction("action.refreshActivity_A");
            sendBroadcast(intent);

            finish();

        }
    }

    private class chang_picture implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            Matisse
                    .from(Setting.this)
                    .choose(MimeType.ofAll())//照片视频全部显示
                    .countable(true)//有序选择图片
                    .maxSelectable(1)//最大选择数量为9
                    // .gridExpectedSize(120)//图片显示表格的大小getResources()
                    .thumbnailScale(0.85f)//缩放比例
                    .theme(R.style.Matisse_Zhihu)//主题  暗色主题 R.style.Matisse_Dracula
                    .imageEngine(new MyGlideEngine())//加载方式
                    .forResult(REQUEST_CODE_CHOOSE);//请求码
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            uri = Matisse.obtainResult(data).get(0);

            upload();
        }
    }

    private void upload() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    pic = bitmapToBase64(MediaStore.Images.Media.getBitmap(getContentResolver(), uri));
                } catch (IOException e) {
                    e.printStackTrace();
                }


                SharedPreferences sharedPreferences = getSharedPreferences(PREFERENCE_NAME, MODE);
                String username = sharedPreferences.getString("username", "1");

                String webContent = WebAccessTools.headpicture(pic, username);
                System.out.println(webContent);
                 get_response= (Get_response) JsonUtil.jsonToObject(webContent,
                        Get_response.class);
                handler.sendEmptyMessage(0x123);
            }

        }).start();

    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (get_response != null && get_response.getMessage().equals("成功")) {
                RequestOptions options = new RequestOptions()
                        .placeholder(R.mipmap.login_pic)		;
                Glide.with(Setting.this).asBitmap().load(uri).apply(options).into(headpicture);
                Intent intent = new Intent();
                intent.setAction("action.refreshActivity_A");
                sendBroadcast(intent);
                Toast.makeText(Setting.this, "发送成功！", Toast.LENGTH_SHORT).show();

            }
        }

        ;
    };


    public static String bitmapToBase64(Bitmap bitmap) {
        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 50, baos);
                baos.flush();
                baos.close();
                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

}
